﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace zVendorControl
{
    public partial class FrmVenSet : Form
    {
        private int _bomid;
        private int _ComponentId;
        public FrmVenSet()
        {
            InitializeComponent();
        }


        #region 加载数据
        public void LoadData( int bomid,int componentid)
        {
            _bomid = bomid; _ComponentId = componentid;
            var sql = @" select inventory.cInvCode,inventory.cInvName,inventory.cInvStd from bom_parent inner join bas_part on bom_parent.ParentId = bas_part.PartId left join Inventory on
            bas_part.InvCode = inventory.cInvCode where BomId =" + _bomid;
            var tmp = Common.handleSQL.getdata(sql);
            if (tmp.Rows.Count > 0)
            {
                this.labmain.Text =string.Format("母件：{0}--{1}--{2}", tmp.Rows[0]["cInvCode"], tmp.Rows[0]["cInvName"], tmp.Rows[0]["cInvStd"]);
            }
            sql = string.Format(@" select inventory.cInvCode,inventory.cInvName,inventory.cInvStd from bom_opcomponent inner join bas_part on bom_opcomponent.ComponentId = bas_part.PartId left join Inventory on
             bas_part.InvCode = inventory.cInvCode
              where BomId = {0} and ComponentId = {1}", _bomid, _ComponentId);
            tmp = Common.handleSQL.getdata(sql);
            if (tmp.Rows.Count > 0)
            {
                this.labdetail.Text =string.Format("子件：{0}--{1}--{2}", tmp.Rows[0]["cInvCode"].GetVal_Str(), tmp.Rows[0]["cInvName"].GetVal_Str(), tmp.Rows[0]["cInvStd"].GetVal_Str());
            }

            sql = "if(object_id('tempdb..#t') is not null) drop table #t";
            Common.handleSQL.execSQL(sql);

            sql = string.Format(@" select bom_opcomponent_vendor.cVenCode,vendor.cVenName,bom_opcomponent_vendor.startDate,
    bom_opcomponent_vendor.expDate into #t from bom_opcomponent_vendor inner join bom_opcomponent on
    (bom_opcomponent.BomId = bom_opcomponent_vendor.BomId
    and bom_opcomponent.ComponentId = bom_opcomponent_vendor.ComponentId)
    left join Vendor on bom_opcomponent_vendor.cVenCode = vendor.cVenCode 
         where bom_opcomponent.BomId={0} and bom_opcomponent.ComponentId={1}", _bomid, _ComponentId);
            tmp = Common.handleSQL.getdata(sql);

            Common.cDataGrid.initGrid("BomVendor", this.superGrid1);
            string strSum;
            
            var strCols = Common.cDataGrid.GetColumnsStr("BomVendor", out strSum);
            sql = "select " + strCols + " from #t  order by cVenCode ";
            var dt_data = Common.handleSQL.getdata(sql);
            int iRowSum = dt_data.Rows.Count;
            this.superGrid1.RowCount = iRowSum + 5;
            for (int i = 0; i < dt_data.Rows.Count; i++)
            {
                this.superGrid1.Rows[i].SetValues(dt_data.Rows[i].ItemArray);
            }
            this.superGrid1.ReadOnly = false;
            this.superGrid1.Columns["cVenCode"].Tag = "editstring";
            this.superGrid1.Columns["startDate"].Tag = "editdate";
            this.superGrid1.Columns["expDate"].Tag = "editdate";
        }
        #endregion

        #region 增行，删行
        private void tsAddRow_Click(object sender, EventArgs e)
        {
            this.superGrid1.Rows.Add(5);
        }

        private void tsDelRow_Click(object sender, EventArgs e)
        {
            this.superGrid1.Rows.Remove(this.superGrid1.CurrentRow);
        }
        #endregion

        #region 供应商参照
        private void superGrid1_bt_Ref_Click(object sender, EventArgs e)
        {
            var colname = this.superGrid1.Columns[this.superGrid1.CurrentCell.ColumnIndex].Name;
            switch(colname)
            {
                case "cVenCode":
                    var cvencode = this.superGrid1.CurrentRow.Cells["cVenCode"].Value.GetVal_Str();
                    var f = new REF.FrmRefVendor();
                    f.RefCode = cvencode;
                    f.ShowDialog(this);
                    this.superGrid1.EditingControl.Text = f.ReturnCode;
                    break;

            }
            
        }


        private void superGrid1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            var colname = this.superGrid1.Columns[this.superGrid1.CurrentCell.ColumnIndex].Name;
            switch (colname)
            {
                case "cVenCode":
                    var ven = e.FormattedValue.GetVal_Str();
                    if (ven.Length == 0) { e.Cancel = false; return; }
                    var sql = "select * from vendor where cVenCode=@cv or cVenName=@cv";
                    var tmp = Common.handleSQL.getdata(sql, new System.Data.SqlClient.SqlParameter("@cv", ven));
                    if (tmp.Rows.Count > 0)
                    {
                        this.superGrid1.Rows[e.RowIndex].Cells["cVenName"].Value = tmp.Rows[0]["cVenName"].GetVal_Str();
                        e.Cancel = false;
                        this.superGrid1.EndEdit();
                    }
                    else
                    {
                        MessageBox.Show("输入的信息有误，请确认！");
                        e.Cancel = true;
                    }
                    var row = this.superGrid1.Rows[e.RowIndex];
                    if (row.Cells["startDate"].Value.GetVal_Str().Length==0)
                    { row.Cells["startDate"].Value = DateTime.Now.ToString("yyyy-MM-dd"); }
                    if (row.Cells["expDate"].Value.GetVal_Str().Length == 0)
                    { row.Cells["expDate"].Value = DateTime.Now.AddYears(3).ToString("yyyy-MM-dd"); }
                    break;
                case "startDate":
                case "expDate":
                    if (this.superGrid1.EditingControl!=null)
                    {
                        var conlist = this.superGrid1.EditingControl.Controls.Find("dtp",true);
                        if (conlist.Length > 0)
                        {
                            var c0 = conlist[0];
                            this.superGrid1.EditingControl.Text = ((DateTimePicker)c0).Value.ToString("yyyy-MM-dd");
                        }
                    }
                    break;
            }

        }
        #endregion

        #region 保存数据
        private void btOK_Click(object sender, EventArgs e)
        {
            try
            {
                var lven = new List<Model.bom_opcomponent_vendor>();
                for (int i = 0; i < this.superGrid1.Rows.Count; i++)
                {

                    var row = this.superGrid1.Rows[i];
                    var cvencode = row.Cells["cVenCode"].Value.GetVal_Str();
                    if (cvencode.Length > 0)
                    {
                        var bomven = new Model.bom_opcomponent_vendor()
                        {
                            cVenCode = cvencode,
                            startDate= row.Cells["startDate"].Value.GetVal_DateTime1(),
                            expDate = row.Cells["expDate"].Value.GetVal_DateTime1()
                        };
                        lven.Add(bomven);
                    }
                }
                var lvenll = lven.Select(s=>s.cVenCode).Distinct().ToList();
                var lvendels = string.Join("','", lvenll.ToArray());
                using (var cn = Common.handleSQL.getConnect())
                {
                    string sql;
                    var cmd = cn.CreateCommand();
                    for (int i = 0; i < lven.Count; i++)
                    {
                        var ven = lven[i];
                        sql = "select cVenCode from vendor where cVenCode=@cVenCode";
                        var vencode = cmd.GetObj(sql, new System.Data.SqlClient.SqlParameter("@cVenCode", ven.cVenCode)).GetVal_Str();
                        if (vencode.Length == 0)
                        {
                            throw new Exception(string.Format("供应商编码【{0}】不正确", vencode));
                        }
                        ven.cVenCode = vencode;
                    }

                    var tran = cn.BeginTransaction();
                    
                    cmd.Transaction = tran;
                    sql = string.Format("delete from bom_opcomponent_vendor where bomid={0} and ComponentId={1} and cVenCode not in ('" + lvendels + "')",
                        _bomid, _ComponentId);
                    cmd.ExecSQL(sql);
                    sql = "select max(autoid) from bom_opcomponent_vendor";
                    var autoid = cmd.GetObj(sql).GetVal_Int() + 1;
                    for (int i = 0; i < lven.Count; i++)
                    {
                        var ven = lven[i];
                        sql = string.Format("select top 1 autoid from bom_opcomponent_vendor where bomid='{0}' and ComponentId='{1}' and cVenCode='{2}'",
                            _bomid, _ComponentId, ven.cVenCode);
                        var tmp = cmd.GetObj(sql).GetVal_Int();
                        if (tmp == 0)
                        {
                            //var bomven = new Model.bom_opcomponent_vendor()
                            //{ AutoID = autoid, BomId = _bomid, ComponentId = _ComponentId, cVenCode = lvenll[i], cMaker = cHandleUF.cUserName, dDate = DateTime.Now,
                            //    expDate = };
                            ven.AutoID = autoid; ven.BomId = _bomid; ven.ComponentId = _ComponentId;
                            ven.cMaker = cHandleUF.cUserName; ven.dDate = DateTime.Now;
                            cmd.InsertData(ven);
                            autoid++;
                        }
                        else
                        {
                            cmd.Update<Model.bom_opcomponent_vendor>(new { startDate = ven.startDate, expDate = ven.expDate, cMaker = cHandleUF.cUserName, dDate = DateTime.Now },
                                s => s.AutoID == tmp);
                        }
                    }
                    tran.Commit();
                }
                MessageBox.Show("保存成功！");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败" + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
            }


        }


        private void btCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion
    }
}
